package com.feihong.yw189.bluetooth.utils.util;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Display;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Tools for handler picture
 *
 * @author Ryan.Tang
 */
public final class ImageTools {
    /**
     * Transfer drawable to bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
                : Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * Bitmap to drawable
     *
     * @param bitmap
     * @return
     */
    public static Drawable bitmapToDrawable(Bitmap bitmap) {
        return new BitmapDrawable(bitmap);
    }

    /**
     * 通过输入流获取图片
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static Bitmap inputStreamToBitmap(InputStream inputStream)
            throws Exception {
        return BitmapFactory.decodeStream(inputStream);
    }
/**
 *Android加载图片时，对于分辨率小，配置低的机子，很容易发生OutOfMemoryError。手机的内存比图片的大很多，怎么会这样？
 *在设置Android虚拟机的内存时：
 *RAM：模拟器的内存空间
 *VM Heap：dalvik虚拟机最大占用内存，也就是单个进程的最大占用内存。
 *VM Heap高配的手机，可能有32M,64M,128M，而低配的手机，一般是16M，分辨率越大的手机，一般分配的也比较多。
 *Android系统对dalvik的vm heapsize作了硬性限制，当Java进程申请的java空间超过阈值时，就会抛出OOM异常。也就是说RAM充足也会发生OOM的异常。
 *--------------------
 *VM Heap大小16mb，当应用加载一张大图时，加载图片所需要的内存空间不是按照图片大小算的，而是按照图片的像素点来算的。
 *图片像素点计算：
 *1张叫juhua.jsp的图片，大小1.27MB，分辨率：3840*2160，24位。
 * Android保存图片像素信息，是用ARGB保存
 * A：0-255,需要一个长度为8的二进制数字，占用1个字节
 * R：0-255,需要一个长度为8的二进制数字，占用1个字节
 * G：0-255,需要一个长度为8的二进制数字，占用1个字节
 * B：0-255,需要一个长度为8的二进制数字，占用1个字节
 *3840*2160*4=33177600字节/1024/1024=31.640MB
 *超过了VM Heap的16MB，报内存溢出
 *10-27 06:16:27.645: I/dalvikvm-heap(1894): Forcing collection of SoftReferences for 33177612-byte allocation
 *10-27 06:16:27.645: E/dalvikvm-heap(1894): Out of memory on a 33177612-byte allocation.
 *10-27 06:16:27.655: E/AndroidRuntime(1894): Caused by: java.lang.OutOfMemoryError
 ************************************
 *解决方法：
 *按比例缩小图片，再加载。
 *现有手机屏幕分辨率 320*480
 *宽比：3840/320=12
 *高比：2160/480=4
 *选择比例大的数字12
 *缩放后再设置，就不会溢出了。
 *31.640MB/12=2.64mb
 */
    /**
     * 根据照片地址对bitmap图片进行压缩
     */
    public static Bitmap yaSuoBitmap(Activity context, String path) {

        Options opts = new Options();
        //默认为false，设为true，则decoder返回null，
        //即BitmapFactory.decodeResource(getResources(),R.drawable.juhua,opts);返回null
        //但会返回图片的参数的信息到Options对象里
        //不解析图片到内存里
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, opts);
        //获取图片的宽，高
        int imageWidth = opts.outWidth;
        int imageHeigth = opts.outHeight;

        //获取屏幕的高宽
        Display dp = context.getWindowManager().getDefaultDisplay();
        //在高版本里有新的方法获取，但图片加载是常用功能，要兼容低版本，所以过时了也用
        int screenWidth = dp.getWidth();
        int screenHeight = dp.getHeight();

        //计算缩放比例
        int scale = 1;
        int scaleWidth = imageWidth / screenWidth;
        int scaleHeight = imageHeigth / screenHeight;

        //取缩放比例，取那个大的值
        if (scaleWidth >= scaleHeight && scaleWidth >= 1) {
            scale = scaleWidth * 3;
        } else if (scaleWidth < scaleHeight && scaleHeight >= 1) {
            scale = scaleHeight * 3;
        }

        //设置缩放比例
        opts.inSampleSize = scale;
        opts.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
        return bitmap;
    }

    /**
     * 字节数组转化为图片
     *
     * @param byteArray
     * @return
     */
    public static Bitmap byteToBitmap(byte[] byteArray) {
        if (byteArray.length != 0) {
            return BitmapFactory
                    .decodeByteArray(byteArray, 0, byteArray.length);
        } else {
            return null;
        }
    }

    /**
     * 字节数组转化为图片
     *
     * @param byteArray
     * @return
     */
    public static Drawable byteToDrawable(byte[] byteArray) {
        ByteArrayInputStream ins = null;
        if (byteArray != null) {
            ins = new ByteArrayInputStream(byteArray);
        }
        return Drawable.createFromStream(ins, null);
    }

    /**
     * 图片转化为字节数组
     *
     * @return
     */
    public static byte[] bitmapToBytes(Bitmap bm) {
        byte[] bytes = null;
        if (bm != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
            bytes = baos.toByteArray();
        }
        return bytes;
    }

    /**
     * 图片转化为字节数组
     *
     * @param drawable
     * @return
     */
    public static byte[] drawableToBytes(Drawable drawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        Bitmap bitmap = bitmapDrawable.getBitmap();
        byte[] bytes = bitmapToBytes(bitmap);
        ;
        return bytes;
    }

    /**
     * 获得圆角图像
     *
     * @param bitmap
     * @param roundPx 5 10
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * Check the SD card
     *
     * @return
     */
    public static boolean checkSDCardAvailable() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }


    /**
     * 保存图片到SD卡
     *
     * @param photoBitmap
     * @param photoName
     * @param path
     */
    public static void savePhotoToSDCard(Bitmap photoBitmap, String path, String photoName) {
        if (checkSDCardAvailable()) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File photoFile = new File(path, photoName + ".png");
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
                        photoFile.getPath();
                        fileOutputStream.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                photoFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除该路径下的所有图片
     */
    public static void deleteAllPhoto(Activity activity, String path) {
        File dir = new File(path);
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            return;
        }
        for (File file : dir.listFiles()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                deleteAllPhoto(activity, path);
            }
//            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//            Uri uri = Uri.fromFile(file);
//            intent.setData(uri);
//            activity.sendBroadcast(intent);
        }
        dir.delete();
    }
}
